<?php

/* 
 * Table/AppHistoryTable.php
 */
namespace RHX\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\AppHistory;

class AppHistoryTable extends AbstractTableGateway{
    protected $table = 'rh_app_history';
    
    /**
     * Constructeur
     * 
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    public function __construct(Adapter $adapter){
        $this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new AppHistory());
	$this->initialize();
    }
    
    /**
     * Tous les enregistrements
     * 
     * @param string $order
     * @param int $perPage
     * @param int $page
     * @return ResultSet
     */
    public function getAll($order = 'id DESC', $perPage = 50, $page = 1){
        return $this->select(function(\Zend\Db\Sql\Select $select)use($order, $perPage, $page){
            $where = new \Zend\Db\Sql\Where();
            $select->order($order);
            $offset	 = ($page - 1) * $perPage;
            $select->offset($offset);
            $select->limit($perPage);
            $select->where($where);
        });
    }
    
    /**
     * Un seul enregistrement
     * 
     * @param int $id
     * @return AppHistory
     */
    public function get($id){
        $row = $this->select(array('id' => $id))->current();
        return ($row) ? null : $row;
    }
    
    /**
     * Enregister une Historique
     * 
     * @param \RHX\Model\Object\AppHistory $history
     * @return int
     */
    public function save(AppHistory $history){
        $data = array(
            'user' => $history->user,
            'machine' => $history->machine,
            'libelle' => $history->libelle,
            'date' => $history->date,
            'heure' => $history->heure,
            'autre' => $history->autre,
        );
        $id = (int)$history->id;
        if($id == 0){
            $this->insert($data);
            return $this->getLastInsertValue();
        }elseif(!is_null($this->get($id))){
            $this->update($data, array('id' => $id));
            return $id;
        }else{
            return 0;
        }
    }
}

